package com.example.demo.common;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 *
 * @author liuhongfeng
 * @date 2019/2/10 11:42
 */
public class DynamicProxyTest {

    interface Subject {
        void sayHi();
        void sayHello();
    }

    static class SubjectImpl implements Subject {

        @Override
        public void sayHi() {
            System.out.println("hi");
        }

        @Override
        public void sayHello() {
            System.out.println("hello");
        }
    }

    // 实现 InvocationHandler 调用处理器接口
    static class ProxyInvocationHandler implements InvocationHandler {
        private Subject target;

        // 代理调用处理器
        public ProxyInvocationHandler(Subject target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.print("say:");
            // 动态执行方法
            return method.invoke(target, args);
        }

    }

    public static void main(String[] args) {
        Subject subject = new SubjectImpl();
        Subject subjectProxy = (Subject) Proxy.newProxyInstance(subject.getClass().getClassLoader(), subject.getClass().getInterfaces(), new ProxyInvocationHandler(subject));
        subjectProxy.sayHi();
        subjectProxy.sayHello();
    }

}
